#include "chatwindow.h"
#include <QPainter>
#include <QPixmap>
#include <QDebug>
#include <QCoreApplication>

// MusicPlayerThread 实现
MusicPlayerThread::MusicPlayerThread(QObject *parent) 
    : QThread(parent), m_playing(false), m_volume(0.5f)
{
    mediaPlayer = new QMediaPlayer;
    audioOutput = new QAudioOutput;
    mediaPlayer->setAudioOutput(audioOutput);
    mediaPlayer->setSource(QUrl("backmusic.mp3"));
    audioOutput->setVolume(m_volume);
    mediaPlayer->setLoops(QMediaPlayer::Infinite);
    
    connect(mediaPlayer, &QMediaPlayer::errorOccurred, this, [this]() {
        emit errorOccurred(mediaPlayer->errorString());
    });
}

MusicPlayerThread::~MusicPlayerThread()
{
    stop();
    wait();
    delete mediaPlayer;
    delete audioOutput;
}

void MusicPlayerThread::run()
{
    exec();
}

void MusicPlayerThread::setVolume(float volume)
{
    QMutexLocker locker(&m_mutex);
    m_volume = volume;
    if (audioOutput) {
        audioOutput->setVolume(m_volume);
    }
}

void MusicPlayerThread::play()
{
    QMutexLocker locker(&m_mutex);
    if (!m_playing) {
        m_playing = true;
        mediaPlayer->play();
    }
}

void MusicPlayerThread::pause()
{
    QMutexLocker locker(&m_mutex);
    if (m_playing) {
        m_playing = false;
        mediaPlayer->pause();
    }
}

void MusicPlayerThread::stop()
{
    QMutexLocker locker(&m_mutex);
    m_playing = false;
    mediaPlayer->stop();
}

void ChatWindow::handleMusicError(const QString &error)
{
    qDebug() << "音乐播放错误:" << error;
    QMessageBox::warning(this, "音乐播放错误", error);
}

// ChatWindow 实现
ChatWindow::ChatWindow(QWidget *parent)
    : QWidget(parent)
{
    setupUI();
    setupNetwork();
    setupModelApiKey();
    
    // 初始化音乐线程
    musicThread = new MusicPlayerThread(this);
    connect(musicThread, &MusicPlayerThread::errorOccurred, this, &ChatWindow::handleMusicError);
    musicThread->start();
    musicThread->play(); // 自动开始播放
}

void ChatWindow::toggleMusic()
{
    performanceTimer.start();
    
    if (musicThread) {
        if (musicToggleButton->text() == "暂停") {
            musicThread->pause();
            musicToggleButton->setText("播放");
        } else {
            musicThread->play();
            musicToggleButton->setText("暂停");
        }
    }
    
    qDebug() << "音乐切换操作耗时:" << performanceTimer.elapsed() << "ms";
}

void ChatWindow::adjustVolume(int value)
{
    float volume = value / 100.0f;
    if (musicThread) {
        musicThread->setVolume(volume);
    }
}

ChatWindow::~ChatWindow()
{
    musicThread->stop();
    delete musicThread;
    delete timer;
    delete networkManager;
}

void ChatWindow::setupUI()
{
    setStyleSheet("QMainWindow { font-size: 24px; color:rgb(189, 42, 9); }");
    setWindowTitle("蕊蕊宝宝专属软件");
    resize(1080, 800);

    // 创建模型选择下拉框
    modelComboBox = new QComboBox(this);
    modelComboBox->addItem("DeepSeek大模型");
    modelComboBox->addItem("腾讯元宝大模型");
    modelComboBox->setStyleSheet("font-size: 16px; color: rgb(121, 24, 100);");

    // 创建时间标签
    timeLabel = new QLabel(this);
    timeLabel->setStyleSheet("font-size: 20px; color: rgb(107, 41, 72);");
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &ChatWindow::updateTime);
    timer->start(1000);
    updateTime();

    // 创建音乐控制按钮
    musicToggleButton = new QPushButton("暂停", this);
    musicToggleButton->setStyleSheet("font-size: 10px; color: rgb(121, 24, 100); background-color: rgb(115, 184, 52);");
    connect(musicToggleButton, &QPushButton::clicked, this, &ChatWindow::toggleMusic);

    // 创建音量调节滑块
    volumeSlider = new QSlider(Qt::Horizontal, this);
    volumeSlider->setRange(0, 100);
    volumeSlider->setValue(50);
    // 设置音量调节滑块的最小宽度，可根据需要调整该值
    volumeSlider->setMinimumWidth(200); 
    volumeSlider->setStyleSheet("font-size: 40px; color: rgb(121, 24, 100); background-color: rgb(115, 184, 52);");
    connect(volumeSlider, &QSlider::valueChanged, this, &ChatWindow::adjustVolume);

    // 将时间标签、音乐控制按钮和音量调节滑块添加到水平布局中
    QHBoxLayout *topLayout = new QHBoxLayout();
    topLayout->addWidget(timeLabel);

    // 添加伸缩项，使进度条和暂停按钮靠右
    topLayout->addStretch(1); 

    topLayout->addWidget(volumeSlider);
    topLayout->addWidget(musicToggleButton);
    topLayout->addStretch(); // 添加伸缩项，将模型选择下拉框推到右边
    topLayout->addWidget(modelComboBox);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(topLayout); // 将顶部布局添加到主布局

    QLabel *titleLabel = new QLabel("蕊蕊宝宝定制版DeepSeek", this);
    titleLabel->setStyleSheet("font-size: 38px; color: rgb(59, 18, 71); background-color:rgb(236, 246, 248);");
    mainLayout->addWidget(titleLabel, 0, Qt::AlignCenter); // 添加标题到主布局

    chatDisplay = new QTextEdit(this);
    chatDisplay->setReadOnly(true);
    QFont font = chatDisplay->font();
    font.setPointSize(16);
    chatDisplay->setFont(font);
    chatDisplay->setStyleSheet("background: transparent;");//设置背景透明
    mainLayout->addWidget(chatDisplay);

    messageInput = new QLineEdit(this);
    messageInput->setStyleSheet("font-size: 20px; color: rgb(199, 175, 195); background-color: rgb(234, 239, 241);");
    messageInput->setPlaceholderText("请蕊蕊宝宝输入后点击发送按钮");

    sendButton = new QPushButton("发送", this);
    sendButton->setStyleSheet("font-size: 20px; color: rgb(121, 24, 100); background-color: rgb(115, 184, 52);");
    connect(sendButton, &QPushButton::clicked, this, &ChatWindow::sendMessage);

    QHBoxLayout *inputLayout = new QHBoxLayout();
    inputLayout->addWidget(messageInput);
    inputLayout->addStretch();
    inputLayout->addWidget(sendButton);

    messageInput->setMinimumWidth(1080);
    sendButton->setMinimumWidth(120);

    mainLayout->addLayout(inputLayout);

    setLayout(mainLayout);

    messageInput->installEventFilter(this);
}

void ChatWindow::setupNetwork()
{
    networkManager = new QNetworkAccessManager(this);
    connect(networkManager, &QNetworkAccessManager::finished, this, &ChatWindow::handleNetworkReply);
}

void ChatWindow::setupModelApiKey()
{
    if (modelComboBox->currentText() == "DeepSeek大模型") {
        apiKey = "sk-7469eef7c40e40108bf3d011b4973ae3";
    } else if (modelComboBox->currentText() == "腾讯元宝大模型") {
        apiKey = "sk-YjWMbnirh1n4u4zx156Oy2QxF5GpZvor5GBLIzNbwcPulODl";
    }
}

QNetworkRequest ChatWindow::createRequest(const QString& apiKey, const QString& model)
{
    QNetworkRequest request;
    if (model == "DeepSeek大模型") {
        request.setUrl(QUrl("https://api.deepseek.com/chat/completions"));
    } else if (model == "腾讯元宝大模型") {
        request.setUrl(QUrl("https://api.hunyuan.cloud.tencent.com/v1/chat/completions"));
    }
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", ("Bearer " + apiKey).toUtf8());
    return request;
}

QJsonObject ChatWindow::createJsonPayload(const QString& message, const QString& model)
{
    QJsonObject jsonObj;
    QJsonArray messagesArray;
    QJsonObject userMessage;
    userMessage["role"] = "user";
    userMessage["content"] = message;
    messagesArray.append(userMessage);
    jsonObj["messages"] = messagesArray;

    if (model == "DeepSeek大模型") {
        jsonObj["model"] = "deepseek-chat";
        jsonObj["frequency_penalty"] = 0;
        jsonObj["max_tokens"] = 2048;
        jsonObj["presence_penalty"] = 0;
        jsonObj["response_format"] = QJsonObject{{"type", "text"}};
        jsonObj["stop"] = QJsonValue::Null;
        jsonObj["stream"] = false;
        jsonObj["stream_options"] = QJsonValue::Null;
        jsonObj["temperature"] = 1;
        jsonObj["top_p"] = 1;
        jsonObj["tools"] = QJsonValue::Null;
        jsonObj["tool_choice"] = "none";
        jsonObj["logprobs"] = false;
        jsonObj["top_logprobs"] = QJsonValue::Null;
    } else if (model == "腾讯元宝大模型") {
        jsonObj["model"] = "hunyuan-turbo";
        jsonObj["enable_enhancement"] = true;
    }
    return jsonObj;
}

void ChatWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    // 使用资源文件路径加载背景图片
    QPixmap pixmap(":/background.jpg");

    if (!pixmap.isNull()) {
        painter.setOpacity(0.5);
        painter.drawPixmap(this->rect(), pixmap);
    } else {
        qDebug() << "Failed to load background image.";
    }
}


bool ChatWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == messageInput && event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) {
            sendMessage();
            return true;
        }
    }
    return QWidget::eventFilter(watched, event);
}

void ChatWindow::sendMessage()
{
    QString message = messageInput->text();
    if (!message.isEmpty()) {
        QTextCharFormat format;
        format.setBackground(QBrush(QColor(218, 112, 181)));

        chatDisplay->setCurrentCharFormat(format);
        chatDisplay->append("蕊蕊宝宝: " + message);
        messageInput->clear();

        setupModelApiKey();
        QString model = modelComboBox->currentText();
        QNetworkRequest request = createRequest(apiKey, model);
        QJsonObject jsonObj = createJsonPayload(message, model);

        QJsonDocument jsonDoc(jsonObj);
        QByteArray jsonData = jsonDoc.toJson();

        networkManager->post(request, jsonData);
    }
}

void ChatWindow::updateTime()
{
    timeLabel->setText("当前时间：" + QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
}

void ChatWindow::handleNetworkReply(QNetworkReply *reply) {
    if (reply->error() != QNetworkReply::NoError) {
        chatDisplay->append("错误: " + reply->errorString());
        reply->deleteLater();
        return;
    }

    QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll());
    QJsonObject jsonObject = jsonResponse.object();

    QString replyMessage;
    QString model = modelComboBox->currentText();
    if (model == "DeepSeek大模型") {
        QJsonArray choicesArray = jsonObject.value("choices").toArray();
        if (choicesArray.isEmpty()) {
            reply->deleteLater();
            return;
        }
        QJsonObject choiceObject = choicesArray.at(0).toObject();
        replyMessage = choiceObject.value("message").toObject().value("content").toString();
    } else if (model == "腾讯元宝大模型") {
        QJsonArray choicesArray = jsonObject.value("choices").toArray();
        if (choicesArray.isEmpty()) {
            reply->deleteLater();
            return;
        }
        QJsonObject choiceObject = choicesArray.at(0).toObject();
        replyMessage = choiceObject.value("message").toObject().value("content").toString();
    }

    // 过滤掉 LaTeX 公式
    replyMessage.remove(QRegularExpression(R"(\$.*?\$)"));

    // 使用智能指针管理 QTextDocument 的生命周期
    std::unique_ptr<QTextDocument> markdownDocument(new QTextDocument(chatDisplay));
    markdownDocument->setMarkdown(replyMessage);

    // 获取 QTextEdit 的 QTextCursor
    QTextCursor editCursor(chatDisplay->document());
    editCursor.movePosition(QTextCursor::End);
    editCursor.insertBlock();

    // 设置背景颜色
    QTextCharFormat format;
    format.setBackground(QBrush(QColor(181, 204, 179)));

    // 插入文本前的格式
    editCursor.insertText(prefix, format);

    // 遍历 markdownDocument 中的所有段落，并设置它们的背景颜色
    for (QTextBlock block = markdownDocument->begin(); block != markdownDocument->end(); block = block.next()) {
        QTextCursor blockCursor(block);
        blockCursor.select(QTextCursor::BlockUnderCursor);
        blockCursor.setCharFormat(format);
    }

    // 插入 Markdown 格式的文本
    QTextDocumentFragment fragment(markdownDocument.get());
    editCursor.insertFragment(fragment);

    // 设置支持表情符号的字体，并保持原始字体样式
    QFont font("Segoe UI Emoji");
    font.setPointSize(chatDisplay->font().pointSize());
    font.setStyle(chatDisplay->font().style());
    chatDisplay->setFont(font);

    // 确保滚动条自动滚动到底部
    chatDisplay->ensureCursorVisible();

    reply->deleteLater();
}